import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter_highlight/flutter_highlight.dart';
import 'package:flutter_highlight/themes/github.dart';
import '../services/api_service.dart';

class FileDetailScreen extends StatefulWidget {
  final String owner;
  final String repo;
  final String sha;
  final String fileName;

  const FileDetailScreen({
    Key? key,
    required this.owner,
    required this.repo,
    required this.sha,
    required this.fileName,
  }) : super(key: key);

  @override
  State<FileDetailScreen> createState() => _FileDetailScreenState();
}

class _FileDetailScreenState extends State<FileDetailScreen> {
  final ApiService _apiService = ApiService();
  bool _isLoading = true;
  String _content = '';
  String? _error;

  @override
  void initState() {
    super.initState();
    _loadFileContent();
  }

  Future<void> _loadFileContent() async {
    try {
      final blob = await _apiService.getFileContent(
        owner: widget.owner,
        repo: widget.repo,
        sha: widget.sha,
      );

      if (blob.encoding == 'base64') {
        final decodedContent = utf8.decode(base64.decode(blob.content));
        setState(() {
          _content = decodedContent;
          _isLoading = false;
        });
      } else {
        setState(() {
          _error = '不支持的编码格式: ${blob.encoding}';
          _isLoading = false;
        });
      }
    } catch (e) {
      setState(() {
        _error = '加载失败: $e';
        _isLoading = false;
      });
    }
  }

  bool get _isMarkdown => widget.fileName.toLowerCase().endsWith('.md');

  // 获取文件类型
  String _getFileType() {
    final extension = widget.fileName.split('.').last.toLowerCase();
    switch (extension) {
      case 'dart':
        return 'dart';
      case 'java':
        return 'java';
      case 'kt':
        return 'kotlin';
      case 'xml':
        return 'xml';
      case 'html':
        return 'html';
      case 'css':
        return 'css';
      case 'js':
        return 'javascript';
      case 'json':
        return 'json';
      case 'yaml':
      case 'yml':
        return 'yaml';
      case 'md':
        return 'markdown';
      case 'gradle':
        return 'gradle';
      case 'properties':
        return 'properties';
      default:
        return 'plaintext';
    }
  }

  // 构建代码高亮组件
  Widget _buildCodeHighlight() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(8),
      ),
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: HighlightView(
          _content,
          language: _getFileType(),
          theme: githubTheme,
          padding: const EdgeInsets.all(8),
          textStyle: const TextStyle(
            fontFamily: 'monospace',
            fontSize: 14,
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.fileName),
        actions: [
          IconButton(
            icon: const Icon(Icons.copy),
            onPressed: _content.isNotEmpty
                ? () {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: Text('已复制到剪贴板')),
                    );
                  }
                : null,
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _error != null
              ? Center(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Text(
                      _error!,
                      style: const TextStyle(color: Colors.red),
                    ),
                  ),
                )
              : _isMarkdown
                  ? Markdown(
                      data: _content,
                      padding: const EdgeInsets.all(16),
                      selectable: true,
                      styleSheet: MarkdownStyleSheet(
                        p: const TextStyle(fontSize: 16),
                        h1: const TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                        ),
                        h2: const TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                        code: TextStyle(
                          backgroundColor: Colors.grey[200],
                          fontFamily: 'monospace',
                        ),
                        codeblockDecoration: BoxDecoration(
                          color: Colors.grey[200],
                          borderRadius: BorderRadius.circular(4),
                        ),
                      ),
                    )
                  : _buildCodeHighlight(),
    );
  }
}
